﻿namespace FiftyOne.Foundation.Mobile.Detection.Wurfl.Handlers
{
    using FiftyOne.Foundation.Mobile.Detection.Wurfl.Matchers;
    using FiftyOne.Foundation.Mobile.Detection.Wurfl.Matchers.ReducedInitialString;
    using System;

    internal abstract class ReducedInitialStringHandler : Handler
    {
        protected ReducedInitialStringHandler()
        {
        }

        protected virtual int CalculateTolerance(string userAgent)
        {
            return FirstSlash(userAgent);
        }

        internal static int FirstSlash(string userAgent)
        {
            int index = userAgent.IndexOf("/");
            return ((index > -1) ? index : userAgent.Length);
        }

        internal static int FirstSpace(string userAgent)
        {
            int index = userAgent.IndexOf(" ");
            return ((index > -1) ? index : userAgent.Length);
        }

        protected internal override Results Match(string userAgent)
        {
            int tolerance = this.CalculateTolerance(userAgent);
            if (tolerance > 0)
            {
                return FiftyOne.Foundation.Mobile.Detection.Wurfl.Matchers.ReducedInitialString.Matcher.Match(userAgent, this, tolerance);
            }
            return null;
        }

        internal static int SecondSlash(string userAgent)
        {
            int index = userAgent.IndexOf("/");
            if (index > -1)
            {
                index = userAgent.IndexOf("/", (int) (index + 1));
            }
            return ((index > -1) ? index : userAgent.Length);
        }
    }
}

